package com.yaojianfeng.openai.controller;

import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/openai")
public class ApiKeyInfoController {


    private String apiKey ="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";

    private final String OPENAI_API_BASE_URL = "https://api.openai.com/v1";
    private final RestTemplate restTemplate;

    public ApiKeyInfoController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    // 查询可用模型
    @GetMapping("/models")
    public ResponseEntity<?> getAvailableModels() {
        String url = OPENAI_API_BASE_URL + "/models";

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey);
        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class);

        return ResponseEntity.ok(response.getBody());
    }

    // 查询 API 使用情况 (例如余额、消耗情况等)
    @GetMapping("/usage")
    public ResponseEntity<?> getUsageInfo(@RequestParam(required = false) String date) {
        //使用Optional来处理日期参数的空值
        Optional<LocalDate> optionalDate = Optional.ofNullable(date).map(LocalDate::parse);
        date = optionalDate.orElse(LocalDate.now()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String url = OPENAI_API_BASE_URL + "/usage?date="+date;

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiKey);
        headers.setDate(System.currentTimeMillis());
        HttpEntity<String> entity = new HttpEntity<>(headers);

        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.GET, entity, Map.class);

        return ResponseEntity.ok(response.getBody());
    }
}
